package com.wiscamp.ninechapters.common.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonHelper {

    static {
        mapper = new ObjectMapper()
                    .registerModule(new ParameterNamesModule())
                    .registerModule(new Jdk8Module())
                    .registerModule(new JavaTimeModule());
    }

    private static final Logger logger = LoggerFactory.getLogger(JsonHelper.class);

    private static ObjectMapper mapper = null;

    public static <T> T toObject(String jsonText, Class<T> valueType) {
        try {
            return mapper.readValue(jsonText, valueType);
        } catch (Exception ex) {
            logger.error("Failed to convert json object.", ex);
        }
        return null;
    }

    public static String toJson(Object value) {
        try {
            return mapper.writeValueAsString(value);
        } catch (Exception ex) {
            logger.error("Failed to write json string.", ex);
        }
        return "";
    }
}
